<?php


namespace app\user\controller;


use app\common\model\AdPlayHistory;
use app\common\model\Ecpm;
use app\common\model\Money;
use app\common\model\UserIncome;
use app\http\middleware\checkTTUserToken;
use think\Controller;
use think\Db;
use think\facade\Request;
use think\facade\Validate;

class Income extends Controller
{


    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class',
//        'app\http\middleware\checkUserAuth::class'
    ];


    //用户个人的收入列表
    public function index()
    {
        //判断昨天的ecpm是否发布了，没发布的话，就返回前天的收益排行
        $page = Request::param('page', 1);
        $user_id = Request::param('user_id');
        $date = Request::param('date');
        $date = strtotime($date);           //传入2020-08-24  表示获取2020-08-24的收益，所以获取的时间应该是add_time为2020-08-25的数据


        $day=60 * 60 * 24;

        //获取的列表
        $list = UserIncome::where([
            ['user_income.user_id', '=', $user_id],
            ['user_income.add_time', '<=', $date+$day*2],
            ['user_income.add_time', '>=', $date+$day  ],
            ['user_income.desc', '=', '激励广告收益'  ],      //只显示激励广告收益
        ])->leftJoin('mini_app','user_income.mini_app_code=mini_app.code')
            ->field(['user_income.*','mini_app.name,mini_app.logo,mini_app.desc'])
            ->page($page, 15)->select();

        $views=0;
        $income=0;
        foreach ($list as $item) {
            $views=$item->views+$views;
            $income=$item->money+$income;
        }

        $data=[
            'views'=>$views,
            'income'=>$income,
            'list'=>$list
        ];

        $this->result( $data, 200, '');

    }

    //提现
    public function takeOut()
    {
        //判断昨天的ecpm是否发布了，没发布的话，就返回前天的收益排行
        $money = Request::param('money', 0);
        $user_id = Request::param('user_id');
        $alipay_name = Request::param('alipay_name',0);
        $alipay_account = Request::param('alipay_account',0);
        $setting=\app\common\model\Setting::getAllSetting();

        //获取我的资金信息
        $wallet = UserIncome::wallet($user_id);

        if (!Validate::checkRule($money, 'require|number')) {
            $this->result('', 400, '金额错误');
        }

        //判断金额是否达到
        if($money<$setting['min_take_out_money']){
            $this->result('', 400, '最低提现金额为'.$setting['min_take_out_money'].'元');
        }

        //提现金额大于可提现的数值
        if ($money > $wallet['can_take_out']) {
            $this->result('', 400, '别逗了，你没这么多钱');
        }
        //生成提现记录
        if (Money::takeOut($user_id, $money,$alipay_name,$alipay_account)) {

            $wallet['can_take_out'] = round($wallet['can_take_out'] - $money, 2);

            $wallet['took_out'] = round($wallet['took_out'], 2);

            $this->result($wallet, 200, '提现申请成功');
        } else {
            $this->result('', 400, '提现申请失败');
        }
    }

    //提现记录列表
    public function takeOutList()
    {
        $user_id = Request::param('user_id');
        $page = Request::param('page');

        $list = Db::table('money_take_out')->where([
            'user_id' => $user_id
        ])->page($page, 20)
            ->order('id', 'desc')
            ->select();

        //整理程序
        for ($i=0;$i<count($list);$i++){
            $status=$list[$i]['status'];
//            -1申请被拒绝 1，申请中，2.提现成功
            if($status==-1){
                $list[$i]['status_text']='申请被拒绝';
            }
            if($status==1){
                $list[$i]['status_text']='申请中';
            }
            if($status==2){
                $list[$i]['status_text']='提现成功';
            }
        }

        $this->result($list, 200, '');
    }

    //用户端data页面的数据
    public function data()
    {
        $user_id = Request::param('user_id');
        $today = today();

        //昨天的完播次数
        $yesterday_views = AdPlayHistory::where([
            ['promote_user_id', '=', $user_id],
            ['add_time', 'BETWEEN', yesterday()]
        ])->count('id');

        //今天的完播次数
        $today_views = AdPlayHistory::where([
            ['promote_user_id', '=', $user_id],
            ['add_time', 'BETWEEN', today()]
        ])->count('id');


        //最新的ecpm，不一定是昨天的，昨天的ecpm
        $yesterday_ecpm = Ecpm::yesterdayEcpm();


        //昨天的ecpm是否已经发布了
        if ($yesterday_ecpm == 0) {
            $day = yesterday();
            $yesterday_ecpm = Ecpm::newestEcpm();       //昨天的ecpm为空，直接返回最新的ecpm代替
        } else {
            $day = today();
        }

        //返回收益排行
        $vip_ad_income_rank = UserIncome::  join('user', 'user_income.user_id=user.id')
            ->where([
                ['user.vip', '=', 1],
                ['user_income.add_time', 'BETWEEN', $day]
            ])->field('user.id as inid,user.username, user.avatar,sum(user_income.money) as money,user_income.mini_app_code,user_income.user_id')
            ->order('money', 'desc')
            ->order('user.id', 'desc')
            ->group('user_id')
            ->limit(10)
            ->select();

        //非会员收益排行
        $ad_income_rank = UserIncome::  join('user', 'user_income.user_id=user.id')
            ->where([
                ['user.vip', '=', 0],
                ['user_income.add_time', 'BETWEEN', $day]
            ])->field('user.id as inid,user.username, user.avatar,sum(user_income.money) as money,user_income.mini_app_code,user_income.user_id')
            ->order('user_income.money', 'desc')
            ->group('user_id')
            ->limit(10)
            ->select();

        // 用户昨天的广告收益
        if ($yesterday_ecpm != 0) {
            $yesterday_ad_income = UserIncome:: where([
                ['user_id', '=', $user_id],
                ['add_time', 'BETWEEN', $today]
            ])->sum('money');
        } else {
            $yesterday_ad_income = '-';
        }

        $yesterday_ad_unit_price = round($yesterday_ecpm / 1000, 4);

        //今日预估的单价
        $avg_ecpme = Db::table('ecpm')->avg('yesterday_ecpm');
        $today_expe_ad_unit_price = round($avg_ecpme / 1000, 4);

        //假数据
        $fake_vip_income = Db::table('fake_income_data')->where(['vip' => 1])->order('money', 'desc')->limit(10)->select();

        //查询设置  返回真假数据
        $setting_real = Db::table('setting')->where(['name'=>'is_real'])->find();
        $vip_rank =  $setting_real['data'] ==1 ? $vip_ad_income_rank :$fake_vip_income;

        //今日预估收益
        $today_expe_total_price = $yesterday_ad_unit_price * $today_views;
        $data = [
            'today_expe_total_price' => $today_expe_total_price,
            'yesterday_views' => $yesterday_views,
            "today_views" => $today_views,
            'yesterday_ecpm' => $yesterday_ecpm == 0 ? "-" : $yesterday_ecpm,
            'yesterday_ad_unit_price' => $yesterday_ad_unit_price,
            "today_expe_ad_unit_price" => $today_expe_ad_unit_price,          //今日预估的单价
            'yesterday_sum_income' => $yesterday_ad_income,
//            "vip_ad_income_rank" => $vip_ad_income_rank,
            "ad_income_rank" => $ad_income_rank,
            "vip_ad_income_rank" => $vip_rank,
            "newestEcpm" => Ecpm::newestEcpm(),
        ];

        $this->result($data, 200, '昨天的收益');
    }

}
